package com.lcj.aoch.rule.service.impl;

import com.lcj.aoch.rule.db.dao.OrderCommentDao;
import com.lcj.aoch.rule.db.dao.OrderDao;
import com.lcj.aoch.rule.db.dao.ProfitsharingRuleDao;
import com.lcj.aoch.rule.db.pojo.ProfitsharingRuleEntity;
import com.lcj.aoch.rule.service.ProfitsharingRuleService;
import com.lcj.common.exception.AochException;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import java.util.HashMap;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ProfitsharingRuleServiceImpl implements ProfitsharingRuleService {
  private static final Logger log = LoggerFactory.getLogger(ProfitsharingRuleServiceImpl.class);
  
  @Resource
  private OrderDao orderDao;
  
  @Resource
  private ProfitsharingRuleDao profitsharingRuleDao;
  
  @Resource
  private OrderCommentDao orderCommentDao;
  
  public HashMap searchProfitsharingRuleById(long a) {
    return this.profitsharingRuleDao.searchProfitsharingRuleById(a);
  }
  
  public HashMap calculateProfitsharing(long orderId, String amount, String msg) {
    long cancelNum = this.orderDao.searchCancelCountInDay(orderId);
    long finishNum = this.orderDao.searchFinishCountInDay(orderId);
    long negativeNum = this.orderCommentDao.searchNegativeCountInDay(orderId);
    log.info("订单编码:{}, 订单总金额{}, 取消订单:{}, 完成订单:{}, 差评数:{}",orderId, amount, cancelNum, finishNum, negativeNum);
    ProfitsharingRuleEntity profitsharingRuleEntity = this.profitsharingRuleDao.searchCurrentRule(msg);
    String rule = profitsharingRuleEntity.getRule();
    log.info("\n分账规则:\n{}", rule);
    ExpressRunner expressRunner = new ExpressRunner();
    DefaultContext defaultContext = new DefaultContext();
    defaultContext.put("cancelNum", Long.valueOf(cancelNum));
    defaultContext.put("negativeNum", Long.valueOf(negativeNum));
    defaultContext.put("finishNum", Long.valueOf(finishNum));
    defaultContext.put("amount", amount);
    try {
      HashMap<String, String> hashMap = (HashMap)expressRunner.execute(rule, (IExpressContext)defaultContext, null, true, false);
      hashMap.put("ruleId", profitsharingRuleEntity.getId().toString());
      return hashMap;
    } catch (Exception e) {
      log.error("计算订单分账失败", e);
      throw new AochException("计算订单分账失败");
    } 
  }
}
